import * as vscode from 'vscode';
import * as path from 'path';
import * as fs from 'fs';
import { spawn, ChildProcess } from 'child_process';

export interface ServerStatusCallback {
    (status: 'stopped' | 'running'): void;
}

export class ServerManager {
    private jgeProcess: ChildProcess | null = null;
    private outputChannel: vscode.OutputChannel;
    private statusCallback: ServerStatusCallback;
    private statusBarItem: vscode.StatusBarItem;

    constructor(outputChannel: vscode.OutputChannel, statusCallback: ServerStatusCallback) {
        this.outputChannel = outputChannel;
        this.statusCallback = statusCallback;
        
        // 创建状态栏项
        this.statusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, 100);
        this.updateStatusBar('stopped');
    }

    public startServer(): void {
        const workspaceFolders = vscode.workspace.workspaceFolders;
        if (!workspaceFolders) {
            vscode.window.showErrorMessage('请先打开一个工作区');
            return;
        }

        const rootPath = workspaceFolders[0].uri.fsPath;
        const jgePath = path.join(rootPath, 'JGE-RS.exe');

        if (!fs.existsSync(jgePath)) {
            vscode.window.showErrorMessage('未找到JGE-RS.exe文件，请确保JGE-RS.exe位于工作区根目录');
            return;
        }

        // 检查文件权限
        try {
            fs.accessSync(jgePath, fs.constants.F_OK | fs.constants.R_OK | fs.constants.X_OK);
        } catch (err) {
            vscode.window.showErrorMessage(`JGE-RS.exe文件权限不足: ${err}`);
            return;
        }

        this.statusCallback('running');
        this.outputChannel.clear();
        this.outputChannel.show();

        this.outputChannel.appendLine(`正在启动JGE-RS.exe，路径: ${jgePath}`);
        this.outputChannel.appendLine(`工作目录: ${rootPath}`);

        try {
            // 使用更详细的spawn配置
            this.jgeProcess = spawn(jgePath, [], {
                cwd: rootPath,
                stdio: ['pipe', 'pipe', 'pipe'],
                windowsHide: false,
                detached: false
            });

            this.outputChannel.appendLine(`进程PID: ${this.jgeProcess.pid}`);

            this.jgeProcess.stdout?.on('data', (data) => {
                const message = data.toString();
                this.outputChannel.append(message);
                this.statusCallback('running');
            });

            this.jgeProcess.stderr?.on('data', (data) => {
                const message = data.toString();
                this.outputChannel.append(message);
            });

            // 监听退出事件，获取更多信息
            this.jgeProcess.on('exit', (code, signal) => {
                this.outputChannel.appendLine(`JGE进程退出 - 退出码: ${code}, 信号: ${signal}`);
                if (code === null && signal === null) {
                    this.outputChannel.appendLine('可能原因: 进程被系统终止或启动后立即崩溃');
                } else if (code === 0) {
                    this.outputChannel.appendLine('进程正常退出');
                } else if (signal) {
                    this.outputChannel.appendLine(`进程被信号 ${signal} 终止`);
                } else {
                    this.outputChannel.appendLine(`进程异常退出，退出码: ${code}`);
                }
            });

            this.jgeProcess.on('close', (code, signal) => {
                this.outputChannel.appendLine(`JGE进程关闭 - 退出码: ${code}, 信号: ${signal}`);
                this.jgeProcess = null;
                this.statusCallback('stopped');
                
                // 如果退出码为null且没有信号，可能是启动失败
                if (code === null && !signal) {
                    vscode.window.showErrorMessage('JGE进程启动后立即退出，请检查程序依赖或配置文件');
                }
            });

            this.jgeProcess.on('error', (err) => {
                this.outputChannel.appendLine(`启动JGE失败: ${err.message}`);
                this.outputChannel.appendLine(`错误类型: ${err.name}`);
                this.jgeProcess = null;
                this.statusCallback('stopped');
                vscode.window.showErrorMessage(`启动JGE失败: ${err.message}`);
            });

        } catch (error) {
            this.statusCallback('stopped');
            this.outputChannel.appendLine(`启动JGE时发生异常: ${error}`);
            vscode.window.showErrorMessage(`启动JGE时发生错误: ${error}`);
        }
    }

    public stopServer(): void {
        if (this.jgeProcess) {
            this.statusCallback('stopped');
            this.jgeProcess.kill('SIGTERM');
            this.jgeProcess = null;
            this.outputChannel.appendLine('JGE进程已停止');
        }
    }

    public toggleServer(): void {
        if (this.jgeProcess && !this.jgeProcess.killed) {
            this.stopServer();
        } else {
            this.startServer();
        }
    }

    public isRunning(): boolean {
        return this.jgeProcess !== null && !this.jgeProcess.killed;
    }

    public dispose(): void {
        this.stopServer();
        this.statusBarItem.dispose();
    }

    private updateStatusBar(status: 'stopped' | 'running'): void {
        switch (status) {
            case 'running':
                this.statusBarItem.text = "$(play) JGE Server 运行中";
                this.statusBarItem.tooltip = "JGE服务端正在运行";
                break;
            default: // stopped
                this.statusBarItem.text = "$(stop) JGE Server 已停止";
                this.statusBarItem.tooltip = "JGE服务端已停止";
        }
        this.statusBarItem.show();
    }
}
